//License: Artistic License v2.0, http://opensource.org/licenses/Artistic-2.0

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/knieriem/markdown"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
)

//example: err := Json("get", userFile, &user)
//example: err := Json("set", userFile, &user)
func Json(directive, fileName string, obj interface{}) error {
	var sliceByte []byte
	var err error
	switch directive {
	case "set":
		{
			if sliceByte, err = json.MarshalIndent(obj, "", ""); err != nil {
				return err
			}
			if err = ioutil.WriteFile(fileName, sliceByte, 0600); err != nil {
				return err
			}
		}
	case "get":
		{
			if sliceByte, err = ioutil.ReadFile(fileName); err != nil {
				return err
			}
			if err = json.Unmarshal(sliceByte, &obj); err != nil {
				return err
			}
		}
	}
	return nil
}

//ListFiles is similar to ls -R, but it does not list the dir names
func ListFiles(name string, fList *[]string) {
	f, err := os.Open(name)
	defer f.Close()
	if err != nil {
		log.Println(err)
		return
	}
	fileInfo, err := f.Stat()
	if err != nil {
		log.Println(err)
		return
	}
	if fileInfo.IsDir() {
		names, err := f.Readdirnames(-1)
		if err != nil {
			log.Println(err)
			return
		}
		for _, sub := range names {
			ListFiles(name+string(os.PathSeparator)+sub, fList)
		}
	} else {
		*fList = append(*fList, name)
	}
}

func Cp(src, dst string) error {
	cmd := exec.Command("cp", "-R", src, dst)
	if os.Getenv("GOOS") == "windows" {
		cmd = exec.Command("copy", src, dst)
	}
	fmt.Println("cp", src, dst)
	return cmd.Run()
}

func Rm(fileName string) error {
	cmd := exec.Command("rm", fileName)
	if os.Getenv("GOOS") == "windows" {
		cmd = exec.Command("del", fileName)
	}
	fmt.Println("rm", fileName)
	return cmd.Run()
}

func ReadFileMarkdownToHTML(fname string) ([]byte, error) {
	f, err := os.Open(fname)
	defer f.Close()
	if err != nil {
		return nil, err
	}
	tempFile, err := ioutil.TempFile(".", "md2html-")
	defer tempFile.Close()
	if err != nil {
		return nil, err
	}
	w := bufio.NewWriter(tempFile)
	p := markdown.NewParser(&markdown.Extensions{Smart: true})
	p.Markdown(f, markdown.ToHTML(w))
	w.Flush()
	byteSlice, err := ioutil.ReadFile(tempFile.Name())
	if err != nil {
		return nil, err
	}
	if err = os.Remove(tempFile.Name()); err != nil {
		return byteSlice, err
	}
	return byteSlice, nil
}

//Copyright: Slamet Hendry
